package com.dhcc.DRGsHosp.pdfRender.utils;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Element;
import com.lowagie2.text.Rectangle;
import com.lowagie2.text.pdf.BaseFont;
import com.lowagie2.text.pdf.PdfContentByte;
import com.lowagie2.text.pdf.PdfGState;
import com.lowagie2.text.pdf.PdfReader;
import com.lowagie2.text.pdf.PdfStamper;

/**
 * @title		:ItextUtils.java
 * @description	:
 * @author		:liqingyang
 * @date		:2016年03月24日
 * @version     :2.1.6
 * @copyright   :DHCC 2013-2016 
 */
public class ItextUtils {

	public static final int SCATTER_FIRST_COUNT_X = 3;  //第一象限X轴数据获取数量
    public static final int SCATTER_FIRST_COUNT_Y = 3;  //第一象限Y轴数据获取数量
    public static final int SCATTER_SECOND_COUNT_X = 3; //第二象限X轴数据获取数量
    public static final int SCATTER_SECOND_COUNT_Y = 3; //第二象限Y轴数据获取数量
    public static final int SCATTER_THIRD_COUNT_X = 3;  //第三象限X轴数据获取数量
    public static final int SCATTER_THIRD_COUNT_Y = 3;  //第三象限Y轴数据获取数量
    public static final int SCATTER_FOURTH_COUNT_X = 3; //第四象限X轴数据获取数量
    public static final int SCATTER_FOURTH_COUNT_Y = 3; //第四象限Y轴数据获取数量
    public static final String PDF_WATER_MARK_NAME = "保密"; //pdf文件水印名称
    
   
	/**
	 * 
	 * @methodname    :getNameShowedOnScatterCharts
	 * @description   :获取象限图中(List)要展示名称的点
	 * @param         :objList:数据集合,avgValue:平均值(DRGs组数、权重),x:x轴的值所在的列数,y:y轴的值所在的列数,scatterCount:获取第几象限的数据
	 * @author        :liqingyang
	 * @return        :InvokeResult
	 * @date          :2016年4月12日
	 */
	
	public static List<String> getNameShowedOnScatterCharts(List<Object[]> objList,double avgValue,int x,int y,int scatterCount){
		
		List<Object[]> scatterFirstList = new ArrayList<Object[]>();
		List<Object[]> scatterSecondList = new ArrayList<Object[]>();
		List<Object[]> scatterThirdList = new ArrayList<Object[]>();
		List<Object[]> scatterFourthList = new ArrayList<Object[]>();
		for (Object[] obj : objList) {
			double xValue = Double.parseDouble(obj[x].toString());
			double yValue = Double.parseDouble(obj[y].toString());
			if(xValue >= 1 && yValue >= avgValue){
				//划分到第一象限二维数组
				scatterFirstList.add(obj);
			}else if(xValue < 1 && yValue > avgValue){
				//划分到第二象限二维数组
				scatterSecondList.add(obj);
			}else if(xValue <= 1 && yValue <= avgValue){
				//划分到第三象限二维数组
				scatterThirdList.add(obj);
			}else if(xValue > 1 && yValue < avgValue){
				//划分到第四象限二维数组
				scatterFourthList.add(obj);
			}
		}
		
		List<String> codeListFirst4x = sortByCol(scatterFirstList,x,SCATTER_FIRST_COUNT_X,"desc");//第一象限X轴数据倒叙排列取前几
		List<String> codeListFirst4y = sortByCol(scatterFirstList,y,SCATTER_FIRST_COUNT_Y,"desc");//第一象限Y轴数据倒叙排列取前几
		List<String> codeListSecond4x = sortByCol(scatterSecondList,x,SCATTER_SECOND_COUNT_X,"");//第二象限X轴数据正序排列取前几
		List<String> codeListSecond4y = sortByCol(scatterSecondList,y,SCATTER_SECOND_COUNT_Y,"desc");//第二象限Y轴数据倒叙排列取前几
		List<String> codeListThird4x = sortByCol(scatterThirdList,x,SCATTER_THIRD_COUNT_X,"");//第三象限X轴数据正序排列取前几
		List<String> codeListThird4y = sortByCol(scatterThirdList,y,SCATTER_THIRD_COUNT_Y,"");//第三象限Y轴数据正序排列取前几
		List<String> codeListFourth4x = sortByCol(scatterFourthList,x,SCATTER_FOURTH_COUNT_X,"desc");//第四象限X轴数据倒叙排列取前几
		List<String> codeListFourth4y = sortByCol(scatterFourthList,y,SCATTER_FOURTH_COUNT_Y,"");//第四象限Y轴数据正叙排列取前几
		
		List<List<String>> paramList = new ArrayList<List<String>>();
		if(scatterCount == 1){//第一象限
			paramList.add(codeListFirst4x);
			paramList.add(codeListFirst4y);
		}else if(scatterCount == 2){//第二象限
			paramList.add(codeListSecond4x);
			paramList.add(codeListSecond4y);
		}else if(scatterCount == 3){//第三象限
			paramList.add(codeListThird4x);
			paramList.add(codeListThird4y);
		}else if(scatterCount == 4){//第四象限
			paramList.add(codeListFourth4x);
			paramList.add(codeListFourth4y);
		}else{//获取所有象限的数据
			paramList.add(codeListFirst4x);
			paramList.add(codeListFirst4y);
			paramList.add(codeListSecond4x);
			paramList.add(codeListSecond4y);
			paramList.add(codeListThird4x);
			paramList.add(codeListThird4y);
			paramList.add(codeListFourth4x);
			paramList.add(codeListFourth4y);
		}
		
		//获取结果集
		List<String> resultList = getScatterResult(paramList);
		return resultList;
	}
	
	/**
	 * 
	 * @methodname    :sortByCol
	 * @description   :对数组集合的指定列进行排序,返回相应数量的code
	 * @param         :data:需要排序的数组集合，sortCol：对第几列进行排序，count：返回多少code
	 * @author        :liqingyang
	 * @return        :InvokeResult
	 * @date          :2016年4月12日
	 */
	private static List<String> sortByCol(List<Object[]> data,int sortCol,int count,String orderType){
		List<String> codeList = new ArrayList<String>();
		String[] temp = new String[10];
		for (int i = 0; i < data.size(); i++) {
			for (int j = 0; j < data.size() - i - 1; j++) {
				if (Double.parseDouble(data.get(j)[sortCol].toString()) > Double.parseDouble(data.get(j + 1)[sortCol].toString())) {
					for (int k = 0; k < data.get(j + 1).length; k++) {
						temp[k] = data.get(j)[k].toString();
						data.get(j)[k] = data.get(j + 1)[k].toString();
						data.get(j + 1)[k] = temp[k];
					}
				}
			}
		}

		//集合数据大于获取的数量
		if(data.size() > count){
			//倒叙排列
			if("desc".equals(orderType)){
				int countDescIndex = 0;
				for (int i = data.size()-1; i >= 0; i--) {
					if(countDescIndex < count){
						codeList.add(data.get(i)[1].toString());
					}else{
						break;
					}
					countDescIndex++;
				}
			}else{//正序排列
				int countIndex = 0;
				for(int i=0;i<data.size();i++){
					if(countIndex < count){
						codeList.add(data.get(i)[1].toString());
					}else{
						break;
					}
					countIndex++;
				}
			}
		}else{//集合数据小于获取的数量，返回所有集合数据
			//倒叙排列
			if("desc".equals(orderType)){
				for (int i = data.size()-1; i >= 0; i--) {
					codeList.add(data.get(i)[1].toString());
				}
			}else{//正序排列
				for(int i=0;i<data.size();i++){
					codeList.add(data.get(i)[1].toString());
				}
			}
		}
			
		
		
		return codeList;
	}
	
	/**
	 * 
	 * @methodname    :getScatterResult
	 * @description   :解析各个象限的数据集合，拼装成List<String>，并过滤重复
	 * @param         :paramList：数据集合
	 * @author        :liqingyang
	 * @return        :List<String>
	 * @date          :2016年4月12日
	 */
	private static List<String> getScatterResult(List<List<String>> paramList){
		List<String> resultList = new ArrayList<String>();
		if(!paramList.isEmpty()){
			for (List<String> list : paramList) {
				if(!list.isEmpty()){
					for (String codFourth4y : list) {
						if(!resultList.contains(codFourth4y)){
							resultList.add(codFourth4y);
						}
					}
				}
			}
		}
		
		return resultList;
	}
	
	 /**
     * @description   :pdf文件添加水印
     * @param inputFile  源文件路径
     * @param outputFile 目标文件路径
     * @param waterMarkName  水印文字内容
     * @param imageFilePath  水印图片的路径
     */
    public static void waterMark(String inputFile, String outputFile,String imageFilePath ) {  
        try {
        	// 待加水印的文件
            PdfReader reader = new PdfReader(inputFile);
            File f = new File(outputFile);
			if (f != null && !f.getParentFile().exists()) {
				f.getParentFile().mkdir();
			}
			// 加完水印的文件
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));  
            
            Rectangle pageRect = null;
            
            //总页数
            int total = reader.getNumberOfPages() + 1;  
            //Image image = Image.getInstance(imageFilePath);  
            //image.setAbsolutePosition(0, 0);//图片位置  
            PdfContentByte under; 
            // 设置字体
    		BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);
            for (int i = 1; i < total; i++) { 
            	pageRect = stamper.getReader(). getPageSizeWithRotation(i);
            	// 计算水印X,Y坐标
            	float x = pageRect.width() / 2;
            	float y = pageRect.height() / 2;
            	//获得PDF最顶层
            	under = stamper.getOverContent(i);
            	under.saveState();
            	
            	//设置透明度
                PdfGState gs = new PdfGState();  
                gs.setFillOpacity(0.1f);//设置透明度为0.1 
                gs.setStrokeOpacity(0.1f);
                under.setGState(gs); 
                
                // 开始
                under.beginText(); 
                //设置水印文字颜色
                under.setColorFill(Color.GRAY); 
                //设置字体及字号
                under.setFontAndSize(base, 280);  
                
                // 水印文字成50度角倾斜
                under.showTextAligned(Element.ALIGN_CENTER,PDF_WATER_MARK_NAME, x+80, y, 50);
                // 字体设置结束  
                under.endText();
                
                
                // 添加图片  
                //under.addImage(image); 
                
            }  
            stamper.close(); 
            System.out.println("---------------修改完毕----------");
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
}
